package com.ruicar.afs.cloud.manage.finance.corporate.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.basic.api.fegin.info.BasicInfoFeign;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.uid.AfsSequenceGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.manage.common.entity.ManageApplyRecord;
import com.ruicar.afs.cloud.manage.common.entity.ManageApprovalRecord;
import com.ruicar.afs.cloud.manage.common.entity.ManagePrepaymentApply;
import com.ruicar.afs.cloud.manage.common.service.ManageApplyRecordService;
import com.ruicar.afs.cloud.manage.common.service.ManageApprovalRecordService;
import com.ruicar.afs.cloud.manage.common.service.ManagePrepaymentApplyService;
import com.ruicar.afs.cloud.manage.finance.bankarrive.entity.ManageAccountRegister;
import com.ruicar.afs.cloud.manage.finance.bankarrive.entity.ManageBankAccount;
import com.ruicar.afs.cloud.manage.finance.bankarrive.service.ManageAccountRegisterService;
import com.ruicar.afs.cloud.manage.finance.bankarrive.service.ManageBankAccountService;
import com.ruicar.afs.cloud.manage.finance.corporate.condition.CaseOperateCondition;
import com.ruicar.afs.cloud.manage.finance.corporate.condition.CorporateTransCondition;
import com.ruicar.afs.cloud.manage.finance.corporate.condition.MachBankArriveListCondition;
import com.ruicar.afs.cloud.manage.finance.corporate.entity.ManageCorporateTransfer;
import com.ruicar.afs.cloud.manage.finance.corporate.service.ManageCorporateTransferService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author ZC.GUO
 * @version 1.0
 * @date create on 2020-07-13 16:50
 */
@Slf4j
@RestController
@Api("对公结算管理")
@RequestMapping("/corporateTransManagement")
@AllArgsConstructor
public class CorporateTransManagementController {

    private final ManageCorporateTransferService manageCorporateTransferService;

    private final ManageBankAccountService manageBankAccountService;

    private final ManageAccountRegisterService manageAccountRegisterService;

    private final AfsSequenceGenerator afsSequenceGenerator;

    private final ManageApprovalRecordService manageApprovalRecordService;

    private final ManageApplyRecordService manageApplyRecordService;

    private final ManagePrepaymentApplyService managePrepaymentApplyService;

    private final BasicInfoFeign basicInfoFeign;

    /**
     * 多条件分页获取对公勾稽案件信息
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/queryCorporateList")
    @ApiOperation(value = "多条件分页获取对公勾稽案件信息")
    public IResponse<IPage<ManageCorporateTransfer>> queryCorporateList(@ModelAttribute CorporateTransCondition corporateTransCondition) {
        if (EmptyUtils.isNotEmpty(corporateTransCondition.getStartTimeS())){
            corporateTransCondition.setStartTimeS(DateUtil.beginOfDay(corporateTransCondition.getStartTimeS()));
        }
        if (EmptyUtils.isNotEmpty(corporateTransCondition.getStartTimeE())){
            corporateTransCondition.setStartTimeE(DateUtil.endOfDay(corporateTransCondition.getStartTimeE()));
        }
        if (EmptyUtils.isNotEmpty(corporateTransCondition.getEndTimeS())){
            corporateTransCondition.setEndTimeS(DateUtil.beginOfDay(corporateTransCondition.getEndTimeS()));
        }
        if (EmptyUtils.isNotEmpty(corporateTransCondition.getEndTimeE())){
            corporateTransCondition.setEndTimeE(DateUtil.endOfDay(corporateTransCondition.getEndTimeE()));
        }
        LambdaQueryWrapper<ManageCorporateTransfer> queryWrapper = Wrappers.<ManageCorporateTransfer>query().lambda()
                .like(EmptyUtils.isNotEmpty(corporateTransCondition.getApplyNo()),ManageCorporateTransfer::getApplyNo,corporateTransCondition.getApplyNo())
                .like(EmptyUtils.isNotEmpty(corporateTransCondition.getCustName()),ManageCorporateTransfer::getCustName,corporateTransCondition.getCustName())
                .like(EmptyUtils.isNotEmpty(corporateTransCondition.getContractNo()),ManageCorporateTransfer::getContractNo,corporateTransCondition.getContractNo())
                .eq(EmptyUtils.isNotEmpty(corporateTransCondition.getCaseSource()),ManageCorporateTransfer::getCaseSource,corporateTransCondition.getCaseSource())
                .eq(EmptyUtils.isNotEmpty(corporateTransCondition.getReceivingBank()),ManageCorporateTransfer::getReceivingBank,corporateTransCondition.getReceivingBank())
                .eq(EmptyUtils.isNotEmpty(corporateTransCondition.getCaseType()),ManageCorporateTransfer::getCaseType,corporateTransCondition.getCaseType())
                .ge(EmptyUtils.isNotEmpty(corporateTransCondition.getStartTimeS()),ManageCorporateTransfer::getStartTime,corporateTransCondition.getStartTimeS())
                .le(EmptyUtils.isNotEmpty(corporateTransCondition.getStartTimeE()),ManageCorporateTransfer::getStartTime,corporateTransCondition.getStartTimeE())
                .ge(EmptyUtils.isNotEmpty(corporateTransCondition.getEndTimeS()),ManageCorporateTransfer::getEndTime,corporateTransCondition.getEndTimeS())
                .le(EmptyUtils.isNotEmpty(corporateTransCondition.getEndTimeE()),ManageCorporateTransfer::getEndTime,corporateTransCondition.getEndTimeE());
        if (!corporateTransCondition.getAllCase()&&EmptyUtils.isEmpty(corporateTransCondition.getCaseStatus())){
            /**  非全部案件并且无指定状态时只查询待处理案件 by ZC.GUO  **/
            queryWrapper.eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.UNDER_REVIEW);
        }else if(corporateTransCondition.getAllCase()&&EmptyUtils.isEmpty(corporateTransCondition.getCaseStatus())){
            /**  全部案件并且无指定状态时本人的未提交案件、全部的(非未提交)案件 by ZC.GUO  **/
            queryWrapper.and(
                    wrapper ->wrapper.and(
                            wra1 ->wra1.eq(ManageCorporateTransfer::getCreateBy,SecurityUtils.getUser().getUsername())
                                    .eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.NOT_SUBMIT)).or()
                            .ne(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.NOT_SUBMIT));
        }else if(EmptyUtils.isNotEmpty(corporateTransCondition.getCaseStatus()) && CaseStatusEnum.NOT_SUBMIT.equals(corporateTransCondition.getCaseStatus())){
            /**  有指定状态且指定状态为未提交时，只能查询本人的未提交案件 by ZC.GUO  **/
            queryWrapper.eq(ManageCorporateTransfer::getCreateBy,SecurityUtils.getUser().getUsername())
                    .eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.NOT_SUBMIT);
        }else{
            /**  有指定状态且指定状态不为未提交时 可以查询符合条件的所有案件 by ZC.GUO  **/
            queryWrapper.eq(ManageCorporateTransfer::getCaseStatus,corporateTransCondition.getCaseStatus());
        }
        queryWrapper.orderByAsc(ManageCorporateTransfer::getStartTime);

        Page page = new Page(corporateTransCondition.getPageNumber(), corporateTransCondition.getPageSize());
        IPage<ManageCorporateTransfer> manageCorporateTransferIPage = manageCorporateTransferService.page(page, queryWrapper);
        return IResponse.success(manageCorporateTransferIPage);
    }
    /**
     * 多条件获取对公勾稽案件信息
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/exportCorporateList")
    @ApiOperation(value = "多条件获取对公勾稽案件信息")
    public IResponse<List<ManageCorporateTransfer>> exportCorporateList(@ModelAttribute CorporateTransCondition corporateTransCondition) {
        if (EmptyUtils.isNotEmpty(corporateTransCondition.getStartTimeS())){
            corporateTransCondition.setStartTimeS(DateUtil.beginOfDay(corporateTransCondition.getStartTimeS()));
        }
        if (EmptyUtils.isNotEmpty(corporateTransCondition.getStartTimeE())){
            corporateTransCondition.setStartTimeE(DateUtil.endOfDay(corporateTransCondition.getStartTimeE()));
        }
        if (EmptyUtils.isNotEmpty(corporateTransCondition.getEndTimeS())){
            corporateTransCondition.setEndTimeS(DateUtil.beginOfDay(corporateTransCondition.getEndTimeS()));
        }
        if (EmptyUtils.isNotEmpty(corporateTransCondition.getEndTimeE())){
            corporateTransCondition.setEndTimeE(DateUtil.endOfDay(corporateTransCondition.getEndTimeE()));
        }
        LambdaQueryWrapper<ManageCorporateTransfer> queryWrapper = Wrappers.<ManageCorporateTransfer>query().lambda()
                .like(EmptyUtils.isNotEmpty(corporateTransCondition.getApplyNo()),ManageCorporateTransfer::getApplyNo,corporateTransCondition.getApplyNo())
                .like(EmptyUtils.isNotEmpty(corporateTransCondition.getCustName()),ManageCorporateTransfer::getCustName,corporateTransCondition.getCustName())
                .like(EmptyUtils.isNotEmpty(corporateTransCondition.getContractNo()),ManageCorporateTransfer::getContractNo,corporateTransCondition.getContractNo())
                .eq(EmptyUtils.isNotEmpty(corporateTransCondition.getCaseSource()),ManageCorporateTransfer::getCaseSource,corporateTransCondition.getCaseSource())
                .eq(EmptyUtils.isNotEmpty(corporateTransCondition.getReceivingBank()),ManageCorporateTransfer::getReceivingBank,corporateTransCondition.getReceivingBank())
                .eq(EmptyUtils.isNotEmpty(corporateTransCondition.getCaseType()),ManageCorporateTransfer::getCaseType,corporateTransCondition.getCaseType())
                .ge(EmptyUtils.isNotEmpty(corporateTransCondition.getStartTimeS()),ManageCorporateTransfer::getStartTime,corporateTransCondition.getStartTimeS())
                .le(EmptyUtils.isNotEmpty(corporateTransCondition.getStartTimeE()),ManageCorporateTransfer::getStartTime,corporateTransCondition.getStartTimeE())
                .ge(EmptyUtils.isNotEmpty(corporateTransCondition.getEndTimeS()),ManageCorporateTransfer::getEndTime,corporateTransCondition.getEndTimeS())
                .le(EmptyUtils.isNotEmpty(corporateTransCondition.getEndTimeE()),ManageCorporateTransfer::getEndTime,corporateTransCondition.getEndTimeE());
        if (!corporateTransCondition.getAllCase()&&EmptyUtils.isEmpty(corporateTransCondition.getCaseStatus())){
            /**  非全部案件并且无指定状态时只查询待处理案件 by ZC.GUO  **/
            queryWrapper.eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.UNDER_REVIEW);
        }else if(corporateTransCondition.getAllCase()&&EmptyUtils.isEmpty(corporateTransCondition.getCaseStatus())){
            /**  全部案件并且无指定状态时本人的未提交案件、全部的(非未提交)案件 by ZC.GUO  **/
            queryWrapper.and(
                    wrapper ->wrapper.and(
                            wra1 ->wra1.eq(ManageCorporateTransfer::getCreateBy,SecurityUtils.getUser().getUsername())
                                    .eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.NOT_SUBMIT)).or()
                            .ne(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.NOT_SUBMIT));
        }else if(EmptyUtils.isNotEmpty(corporateTransCondition.getCaseStatus()) && CaseStatusEnum.NOT_SUBMIT.equals(corporateTransCondition.getCaseStatus())){
            /**  有指定状态且指定状态为未提交时，只能查询本人的未提交案件 by ZC.GUO  **/
            queryWrapper.eq(ManageCorporateTransfer::getCreateBy,SecurityUtils.getUser().getUsername())
                    .eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.NOT_SUBMIT);
        }else{
            /**  有指定状态且指定状态不为未提交时 可以查询符合条件的所有案件 by ZC.GUO  **/
            queryWrapper.eq(ManageCorporateTransfer::getCaseStatus,corporateTransCondition.getCaseStatus());
        }
        queryWrapper.orderByAsc(ManageCorporateTransfer::getStartTime);
        List<ManageCorporateTransfer> manageCorporateTransferList = manageCorporateTransferService.list(queryWrapper);
        return IResponse.success(manageCorporateTransferList);
    }
    /**
     * 根据案件编号查询对公结算案件详情
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/queryCorporateByCaseNo")
    @ApiOperation(value = "根据案件编号查询对公结算案件详情")
    public IResponse<ManageCorporateTransfer> queryCorporateByCaseNo(@RequestParam("caseNo") String caseNo) {
        ManageCorporateTransfer manageCorporateTransfer = manageCorporateTransferService.getOne(Wrappers.<ManageCorporateTransfer>query().lambda()
                .eq(ManageCorporateTransfer::getCaseNo,caseNo)
        );
        if (EmptyUtils.isEmpty(manageCorporateTransfer)){
            manageCorporateTransfer = new ManageCorporateTransfer();
        }
        return IResponse.success(manageCorporateTransfer);
    }
    /**
     * 对公勾稽案件信息保存
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/saveCorporate")
    @ApiOperation(value = "对公勾稽案件信息保存")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<ManageCorporateTransfer> saveCorporate(@RequestBody ManageCorporateTransfer corporateTransfer) {
        /**  生成案件编号 by ZC.GUO  **/
        if (EmptyUtils.isEmpty(corporateTransfer.getCaseNo())){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            Long seqNo = afsSequenceGenerator.genNext("DGJS",dateFormat.format(Calendar.getInstance().getTime()));
            String seqStr = StringUtils.leftPad(seqNo.toString(),4,"0");
            String caseNo = "DGJS" + dateFormat.format(Calendar.getInstance().getTime()) + seqStr;
            corporateTransfer.setCaseNo(caseNo);

        }
        /**  案件状态 by ZC.GUO  **/
        corporateTransfer.setCaseStatus(CaseStatusEnum.NOT_SUBMIT);
        corporateTransfer.setIsOperating(YesOrNoEnum.no);

        manageCorporateTransferService.saveOrUpdate(corporateTransfer);

        /**  保存变更操作记录数据 by ZC.GUO  **/
        ManageApplyRecord applyRecord = manageApplyRecordService.getOne(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getCaseNo, corporateTransfer.getCaseNo()));
        if (EmptyUtils.isNotEmpty(applyRecord)){
            applyRecord.setCaseStatus(CaseStatusEnum.NOT_SUBMIT);
            manageApplyRecordService.updateById(applyRecord);
        }else{
            ManageApplyRecord record = new ManageApplyRecord();
            record.setContractNo(corporateTransfer.getContractNo());
            record.setCaseNo(corporateTransfer.getCaseNo());
            record.setContractBusiness(CaseTypeEnum.BEFORE_CHARGE.equals(corporateTransfer.getCaseType())?ContractBusinessEnum.corporateSettlementPrepayment:ContractBusinessEnum.corporateSettlementRent);
            record.setCaseStatus(CaseStatusEnum.NOT_SUBMIT);
            record.setDataSource(corporateTransfer.getDataSource());
            record.setBusinessSource(corporateTransfer.getCaseSource());
            manageApplyRecordService.save(record);
        }

        if (EmptyUtils.isEmpty(corporateTransfer)){
            corporateTransfer = new ManageCorporateTransfer();
        }
        return IResponse.success(corporateTransfer);
    }
    /**
     * 对公勾稽案件信息提交
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/submitCorporate")
    @ApiOperation(value = "对公勾稽案件信息提交")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<String> submitCorporate(@RequestBody ManageCorporateTransfer corporateTransfer) {

        /**  合同关闭（审核中、审批通过） by ZC.GUO  **/
        List<ManageApplyRecord> list = manageApplyRecordService.list(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getContractNo, corporateTransfer.getContractNo())
                .eq(ManageApplyRecord::getContractBusiness, ContractBusinessEnum.closeContract)
                .in(ManageApplyRecord::getCaseStatus, CaseStatusEnum.UNDER_REVIEW, CaseStatusEnum.APPROVED));
        if (list.size() > 0) {
            throw new AfsBaseException("合同关闭业务审核中，无法审批！");
        }


        /**  生成案件编号 by ZC.GUO  **/
        if (EmptyUtils.isEmpty(corporateTransfer.getCaseNo())){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            Long seqNo = afsSequenceGenerator.genNext("DGJS",dateFormat.format(Calendar.getInstance().getTime()));
            String seqStr = StringUtils.leftPad(seqNo.toString(),4,"0");
            String caseNo = "DGJS" + dateFormat.format(Calendar.getInstance().getTime()) + seqStr;
            corporateTransfer.setCaseNo(caseNo);
        }
        /**  案件状态 by ZC.GUO  **/
        corporateTransfer.setCaseStatus(CaseStatusEnum.UNDER_REVIEW);
        /**  开始时间 by ZC.GUO  **/
        corporateTransfer.setStartTime(Calendar.getInstance().getTime());
        corporateTransfer.setIsOperating(YesOrNoEnum.no);

        manageCorporateTransferService.saveOrUpdate(corporateTransfer);

        /**  保存变更操作记录数据 by ZC.GUO  **/
        ManageApplyRecord applyRecord = manageApplyRecordService.getOne(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getCaseNo, corporateTransfer.getCaseNo()));
        if (EmptyUtils.isNotEmpty(applyRecord)){
            applyRecord.setCaseStatus(CaseStatusEnum.UNDER_REVIEW);
            applyRecord.setApplyTime(DateUtil.date());
            manageApplyRecordService.updateById(applyRecord);
        }else{
            ManageApplyRecord record = new ManageApplyRecord();
            record.setContractNo(corporateTransfer.getContractNo());
            record.setCaseNo(corporateTransfer.getCaseNo());
            record.setContractBusiness(CaseTypeEnum.BEFORE_CHARGE.equals(corporateTransfer.getCaseType())?ContractBusinessEnum.corporateSettlementPrepayment:ContractBusinessEnum.corporateSettlementRent);
            record.setCaseStatus(CaseStatusEnum.UNDER_REVIEW);
            record.setDataSource(corporateTransfer.getDataSource());
            record.setBusinessSource(corporateTransfer.getCaseSource());
            record.setApplyTime(DateUtil.date());
            manageApplyRecordService.save(record);
        }

        /**  保存操作流水 by ZC.GUO  **/
        ManageApprovalRecord approvalRecord = new ManageApprovalRecord();
        approvalRecord.setContractNo(corporateTransfer.getContractNo());
        approvalRecord.setCaseNo(corporateTransfer.getCaseNo());
        approvalRecord.setContractBusiness(CaseTypeEnum.BEFORE_CHARGE.equals(corporateTransfer.getCaseType())?ContractBusinessEnum.corporateSettlementPrepayment:ContractBusinessEnum.corporateSettlementRent);
        approvalRecord.setProcessPerson(SecurityUtils.getUser().getUserRealName());
        approvalRecord.setDepartment(SecurityUtils.getUser().getDeptId().toString());
        approvalRecord.setBizDataId(String.valueOf(corporateTransfer.getId()));

        approvalRecord.setProcessNode(null);
        approvalRecord.setNodeName("发起对公结算");
        approvalRecord.setApprovalOpinion("发起对公结算");
        manageApprovalRecordService.save(approvalRecord);

        return IResponse.success("提交成功");
    }


    /**
     * 删除指定对公案件
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/deleteCorporateTransfer")
    @ApiOperation(value = "删除对公案件")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<String> deleteCorporateTransfer(@ModelAttribute CorporateTransCondition corporateTransCondition) {
        ManageCorporateTransfer manageCorporateTransfer = manageCorporateTransferService.getById(corporateTransCondition.getId());
        if (manageCorporateTransfer != null && CaseStatusEnum.NOT_SUBMIT.equals(manageCorporateTransfer.getCaseStatus())){
            manageCorporateTransferService.removeById(manageCorporateTransfer.getId());
            return IResponse.success("删除成功");
        }else{
            return IResponse.fail("删除失败");
        }
    }

    /**
     * 审核通过操作的校验
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/agreeCorporateValid")
    @ApiOperation(value = "审核通过操作的校验")
    public IResponse<JSON> agreeCorporateValid(@ModelAttribute CaseOperateCondition caseOperateCondition) {
        ManageCorporateTransfer corporateTransfer = manageCorporateTransferService.getOne(Wrappers.<ManageCorporateTransfer>query().lambda()
                .eq(ManageCorporateTransfer::getId,caseOperateCondition.getCaseId())
                .eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.UNDER_REVIEW)
        );
        if(EmptyUtils.isEmpty(corporateTransfer)){
            return IResponse.fail("案件已经被审核，操作失败");
        }
        /**  合同状态校验 by ZC.GUO  **/
        if (DataSourceEnum.icos.equals(corporateTransfer.getDataSource())){
            IResponse<String> response = basicInfoFeign.getContractStatusByContractNo(corporateTransfer.getContractNo());
            if (CommonConstants.SUCCESS.equals(response.getCode())){
                String contractStatusStr = response.getData();
                ContractStatusEnum contractStatus = ContractStatusEnum.valueOf(contractStatusStr);
                if (ContractStatusEnum.advanceSettle.equals(contractStatus)
                        || ContractStatusEnum.contractCancel.equals(contractStatus)
                        || ContractStatusEnum.normalSettle.equals(contractStatus)){
                    throw new AfsBaseException("合同状态为"+contractStatus.getDesc()+"，本业务不能通过");
                }

            }else{
                throw new AfsBaseException("合同状态校验失败，请稍后重试");
            }
        }
        /**  提前结清业务校验（审核总） by ZC.GUO  **/
        ManagePrepaymentApply prepaymentApply = managePrepaymentApplyService.getOne(Wrappers.<ManagePrepaymentApply>query().lambda()
                .eq(ManagePrepaymentApply::getContractNo,corporateTransfer.getContractNo())
                .eq(ManagePrepaymentApply::getApplyStatus,CaseStatusEnum.UNDER_REVIEW)
        );
        if (EmptyUtils.isNotEmpty(prepaymentApply)){
            if (CaseTypeEnum.RENT.equals(corporateTransfer.getCaseType())){
                throw new AfsBaseException("提前结清业务审核中，无法审批");
            }
        }
        /**  提前结清业务校验（审核通过，未过还款日） by ZC.GUO  **/
        prepaymentApply = managePrepaymentApplyService.getOne(Wrappers.<ManagePrepaymentApply>query().lambda()
                .eq(ManagePrepaymentApply::getContractNo,corporateTransfer.getContractNo())
                .eq(ManagePrepaymentApply::getApplyStatus,CaseStatusEnum.APPROVED)
                .eq(ManagePrepaymentApply::getStatus,ValidOrInvalidEnum.valid)
        );
        if (EmptyUtils.isNotEmpty(prepaymentApply)){
            if (CaseTypeEnum.RENT.equals(corporateTransfer.getCaseType())){
                JSON res = JSONUtil.parse("{}");
                res.putByPath("result","0");
                res.putByPath("msg","已申请提前结清业务，请谨慎操作！");
                return IResponse.success(res);
            }
        }

        /**  提前结清对公收款（审核中） by ZC.GUO  **/
        List<ManageCorporateTransfer> corporateTransferList = manageCorporateTransferService.list(Wrappers.<ManageCorporateTransfer>query().lambda()
                .eq(ManageCorporateTransfer::getContractNo,corporateTransfer.getContractNo())
                .ne(ManageCorporateTransfer::getId,corporateTransfer.getId())
                .eq(ManageCorporateTransfer::getCaseType,CaseTypeEnum.BEFORE_CHARGE)
                .eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.UNDER_REVIEW)
        );
        if (EmptyUtils.isNotEmpty(corporateTransferList)){
            if (CaseTypeEnum.BEFORE_CHARGE.equals(corporateTransfer.getCaseType())){
                throw new AfsBaseException("已申请对公收款（提前结清类）业务，无法审批！");
            }else{
                throw new AfsBaseException("已申请对公收款（月供类）业务，无法审批！");
            }
        }
        /**  合同取消（审核中、审批通过） by ZC.GUO  **/
        List<ManageApplyRecord> list = manageApplyRecordService.list(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getContractNo, corporateTransfer.getContractNo())
                .eq(ManageApplyRecord::getContractBusiness, ContractBusinessEnum.cancelContract)
                .in(ManageApplyRecord::getCaseStatus, CaseStatusEnum.UNDER_REVIEW, CaseStatusEnum.APPROVED));
        if (list.size() > 0) {
            throw new AfsBaseException("合同取消业务审核中，无法审批！");
        }
        /**  合同关闭（审核中、审批通过） by ZC.GUO  **/
        list = manageApplyRecordService.list(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getContractNo, corporateTransfer.getContractNo())
                .eq(ManageApplyRecord::getContractBusiness, ContractBusinessEnum.closeContract)
                .in(ManageApplyRecord::getCaseStatus, CaseStatusEnum.UNDER_REVIEW, CaseStatusEnum.APPROVED));
        if (list.size() > 0) {
            throw new AfsBaseException("合同关闭业务审核中，无法审批！");
        }
        /**  撤销收款（审核中、审批通过） by ZC.GUO  **/
        list = manageApplyRecordService.list(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getContractNo, corporateTransfer.getContractNo())
                .eq(ManageApplyRecord::getContractBusiness, ContractBusinessEnum.collectionRevoke)
                .eq(ManageApplyRecord::getCaseStatus, CaseStatusEnum.UNDER_REVIEW));
        if (list.size() > 0) {
            throw new AfsBaseException("撤销收款业务审核中，无法审批！");
        }
        /**  豁免类（审核中） by ZC.GUO  **/
        list = manageApplyRecordService.list(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getContractNo, corporateTransfer.getContractNo())
                .in(ManageApplyRecord::getContractBusiness, ContractBusinessEnum.costExempt,ContractBusinessEnum.costExemptBill,ContractBusinessEnum.exemptTypes)
                .eq(ManageApplyRecord::getCaseStatus, CaseStatusEnum.UNDER_REVIEW));
        if (list.size() > 0) {
            throw new AfsBaseException("豁免业务审核中，无法审批！");
        }
        /**  宽限期调整类（审核中） by ZC.GUO  **/
        list = manageApplyRecordService.list(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getContractNo, corporateTransfer.getContractNo())
                .eq(ManageApplyRecord::getContractBusiness, ContractBusinessEnum.gracePeriodAdjustment)
                .eq(ManageApplyRecord::getCaseStatus, CaseStatusEnum.UNDER_REVIEW));
        if (list.size() > 0) {
            if (CaseTypeEnum.RENT.equals(corporateTransfer.getCaseType())){
                JSON res = JSONUtil.parse("{}");
                res.putByPath("result","0");
                res.putByPath("msg","宽限期业务审核中，请谨慎操作！");
                return IResponse.success(res);
            }
        }
        JSON res = JSONUtil.parse("{}");
        res.putByPath("result","1");
        res.putByPath("msg","校验通过");
        return IResponse.success(res);
    }
    /**
     * 案件审核通过
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/agreeSubmit")
    @ApiOperation(value = "案件审核通过")
    public IResponse<String> agreeSubmit(@ModelAttribute CaseOperateCondition caseOperateCondition) {
        ManageCorporateTransfer corporateTransfer = manageCorporateTransferService.getOne(Wrappers.<ManageCorporateTransfer>query().lambda()
                .eq(ManageCorporateTransfer::getId,caseOperateCondition.getCaseId())
                .eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.UNDER_REVIEW)
        );
        if(EmptyUtils.isEmpty(corporateTransfer)){
            return IResponse.fail("案件已经被审核，操作失败");
        }
        List<AccountRegistStatusEnum> statusEnumList = new ArrayList<>();
        statusEnumList.add(AccountRegistStatusEnum.ALREADY_GENERA);
        statusEnumList.add(AccountRegistStatusEnum.WRITE_BACK);
        List<Long> idList = Arrays.stream(caseOperateCondition.getIds().split(",")).map(s ->Long.parseLong(s.trim())).collect(Collectors.toList());
        List<ManageAccountRegister> manageAccountRegisterList = manageAccountRegisterService.list(Wrappers.<ManageAccountRegister>query().lambda()
                .in(ManageAccountRegister::getId,idList)
                .in(ManageAccountRegister::getStatus,statusEnumList)
        );
        if (EmptyUtils.isEmpty(manageAccountRegisterList) || idList.size() != manageAccountRegisterList.size()){
            return IResponse.fail("银行到账记录已使用，请刷新列表重试");
        }
        /**  记录锁定 by ZC.GUO  **/
        corporateTransfer.setIsOperating(YesOrNoEnum.yes);
        if (manageCorporateTransferService.lockOrUnlockCorporateTransfer(corporateTransfer)){
            try{
                /**  到账记录锁定 by ZC.GUO  **/
                if (EmptyUtils.isNotEmpty(idList) && manageAccountRegisterService.lockAccountRegister(idList)){
                    manageCorporateTransferService.agreeSubmit(caseOperateCondition,corporateTransfer);
                    return IResponse.success("对公结算案件审核通过");
                }else{
                    return IResponse.fail("银行到账记录已使用，请刷新列表重试");
                }
            }catch (Exception e){
                log.error("对公结算{}审核失败！",corporateTransfer.getCaseNo());
                return IResponse.fail("操作失败");
            }finally{
                /**  无论如何都要解锁 by ZC.GUO  **/
                corporateTransfer.setIsOperating(YesOrNoEnum.no);
                manageCorporateTransferService.lockOrUnlockCorporateTransfer(corporateTransfer);
                /**  到账记录解锁 by ZC.GUO  **/
                manageAccountRegisterService.unlockAccountRegister(idList);
            }
        }else{
            return IResponse.fail("该申请正在由他人审批，请刷新列表重试");
        }
    }
    /**
     * 案件审核拒绝
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/refuseSubmit")
    @ApiOperation(value = "案件审核拒绝")
    public IResponse<String> refuseSubmit(@ModelAttribute CaseOperateCondition caseOperateCondition) {
        /**  案件信息更新 by ZC.GUO  **/
        ManageCorporateTransfer corporateTransfer = manageCorporateTransferService.getOne(Wrappers.<ManageCorporateTransfer>query().lambda()
                .eq(ManageCorporateTransfer::getId,caseOperateCondition.getCaseId())
                .eq(ManageCorporateTransfer::getCaseStatus,CaseStatusEnum.UNDER_REVIEW)
        );
        if(EmptyUtils.isEmpty(corporateTransfer)){
            return IResponse.fail("案件已经被审核，操作失败");
        }
        /**  记录锁定 by ZC.GUO  **/
        corporateTransfer.setIsOperating(YesOrNoEnum.yes);
        if (manageCorporateTransferService.lockOrUnlockCorporateTransfer(corporateTransfer)){
            try{
                manageCorporateTransferService.refuseSubmit(caseOperateCondition,corporateTransfer);
                return IResponse.success("对公结算案件拒绝");
            }catch (Exception e){
                log.error("对公结算{}审核失败！",corporateTransfer.getCaseNo());
                return IResponse.fail("操作失败");
            }finally{
                /**  无论如何都要解锁 by ZC.GUO  **/
                corporateTransfer.setIsOperating(YesOrNoEnum.no);
                manageCorporateTransferService.lockOrUnlockCorporateTransfer(corporateTransfer);
            }
        }else{
            return IResponse.fail("该申请正在由他人审批，请刷新列表重试");
        }
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }


    /**
     * 为对公勾稽案件匹配银行到账记录
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/machBankArriveList")
    @ApiOperation(value = "为对公勾稽案件匹配银行到账记录")
    public IResponse<List<ManageAccountRegister>> machBankArriveList(@ModelAttribute MachBankArriveListCondition condition) {

        if (EmptyUtils.isNotEmpty(condition.getBankCode())){
            /**  账号列表 by ZC.GUO  **/
            List<ManageBankAccount> manageBankAccountList = manageBankAccountService.list(Wrappers.<ManageBankAccount>query().lambda()
                    .eq(ManageBankAccount::getBankCode,condition.getBankCode())
            );
            List<String> bankAccountList = new ArrayList<>();
            if (EmptyUtils.isNotEmpty(manageBankAccountList)){
                for (ManageBankAccount bankAccount:manageBankAccountList){
                    bankAccountList.add(bankAccount.getAccount());
                }

            }
            /**  空list处理 by ZC.GUO  **/
            if (EmptyUtils.isEmpty(bankAccountList)){
                bankAccountList.add("");
            }
            condition.setBankAccountList(bankAccountList);
        }
        /**  开始时间和结束时间 by ZC.GUO  **/
        if (EmptyUtils.isNotEmpty(condition.getStartDate())){
            condition.setStartDate(DateUtil.beginOfDay(condition.getStartDate()));
        }
        if (EmptyUtils.isNotEmpty(condition.getEndDate())){
            condition.setEndDate(DateUtil.endOfDay(condition.getEndDate()));
        }


        List<AccountRegistStatusEnum> statusEnumList = new ArrayList<>();
        statusEnumList.add(AccountRegistStatusEnum.ALREADY_GENERA);
        List<ManageAccountRegister> accountRegisterList = manageAccountRegisterService.list(Wrappers.<ManageAccountRegister>query().lambda()
                .eq(EmptyUtils.isNotEmpty(condition.getArriveBank()),ManageAccountRegister::getBankAccount,condition.getArriveBank())
                .in(EmptyUtils.isNotEmpty(condition.getBankCode()),ManageAccountRegister::getBankAccount,condition.getBankAccountList())
                .ge(EmptyUtils.isNotEmpty(condition.getAmtBottom()),ManageAccountRegister::getReceivedAmt,condition.getAmtBottom())
                .le(EmptyUtils.isNotEmpty(condition.getAmtTop()),ManageAccountRegister::getReceivedAmt,condition.getAmtTop())
                .like(EmptyUtils.isNotEmpty(condition.getCustName()),ManageAccountRegister::getPaymentCust,condition.getCustName())
                .like(EmptyUtils.isNotEmpty(condition.getCustAccount()),ManageAccountRegister::getCustAccount,condition.getCustAccount())
                .ge(EmptyUtils.isNotEmpty(condition.getStartDate()),ManageAccountRegister::getArrivalTime,condition.getStartDate())
                .le(EmptyUtils.isNotEmpty(condition.getEndDate()),ManageAccountRegister::getArrivalTime,condition.getEndDate())
                .in(ManageAccountRegister::getStatus,statusEnumList)
                .orderByAsc(ManageAccountRegister::getArrivalTime)
        );
        return IResponse.success(accountRegisterList);
    }

}
